package com.example.myapplication.network;

import android.content.Context;
import com.example.myapplication.utils.TokenManager;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 认证拦截器
 * 自动为需要认证的API请求添加Authorization头
 */
public class AuthInterceptor implements Interceptor {
    
    private TokenManager tokenManager;
    
    public AuthInterceptor(Context context) {
        this.tokenManager = new TokenManager(context);
    }
    
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request originalRequest = chain.request();
        
        // 检查是否需要添加认证头（排除登录接口）
        String url = originalRequest.url().toString();
        if (url.contains("/api/auth/login")) {
            // 登录接口不需要认证头
            return chain.proceed(originalRequest);
        }
        
        // 获取token
        String token = tokenManager.getToken();
        if (token != null && !token.isEmpty()) {
            // 添加认证头
            Request authenticatedRequest = originalRequest.newBuilder()
                    .header("X-Authorization", "Bearer " + token)
                    .build();
            return chain.proceed(authenticatedRequest);
        }
        
        // 如果没有token，直接发送原始请求
        return chain.proceed(originalRequest);
    }
}
